package com.lmuse.xmr.foodspotting.db;

import com.lmuse.xmr.foodspotting.model.Recipe;
import com.lmuse.xmr.foodspotting.model.User;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

public class CollectPresenterImpl implements Contract.CollectPresenter {

    private Contract.CollectView collectView;

    public CollectPresenterImpl(Contract.CollectView collectView) {
        this.collectView = collectView;
    }

    @Override
    public void collectRecipe(String recipeId) {
        User user = BmobUser.getCurrentUser(User.class);
        //把菜谱添加到用户表的collecting字段中
        BmobRelation relation = new BmobRelation();
        Recipe recipe = new Recipe();
        recipe.setObjectId(recipeId);
        relation.add(recipe);
        //多对多关联指向collecting字段
        user.setCollecting(relation);
        user.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    collectView.onCollectRecipeSuccess();
                }  else {
                    collectView.onCollectRecipeFailed(e.toString());
                }
            }
        });
    }

    @Override
    public void cancelCollectRecipe(String recipeId) {
        User user = BmobUser.getCurrentUser(User.class);
        Recipe recipe = new Recipe();
        recipe.setObjectId(recipeId);
        BmobRelation relation = new BmobRelation();
        //取消收藏也就是从relation中删除一个recipe对象
        relation.remove(recipe);
        //重新设置指向
        user.setCollecting(relation);
        user.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    collectView.onCancelCollectSuccess();
                }else {
                    collectView.onCancelCollectFailed(e.toString());
                }
            }
        });
    }

    @Override
    public void queryCollecting() {
        BmobQuery<Recipe> query = new BmobQuery<>();
        User user = BmobUser.getCurrentUser(User.class);
        //TODO 不友好
        query.addWhereRelatedTo("collecting", new BmobPointer(user));
        query.findObjects(new FindListener<Recipe>() {
            @Override
            public void done(List<Recipe> list, BmobException e) {
                if (e == null) {
                    collectView.onQueryCollectingSuccess(list);
                } else {
                    collectView.onQueryCollectingFailed(e.toString());
                }
            }
        });
    }

    @Override
    public void onDetach() {

    }
}
